package com.scidpro.util;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class BooksJsonParser {

	private static final String BOOKS = "books";
	private static final String ID = "id";
	private static final String NAME = "name";
	private static final String PRICE = "price";
	private static final String DESCRIPTION = "description";
	private static final String URL = "url";

	public static ArrayList<Book> convertJsonToBooksList(String json) {
		ArrayList<Book> list = new ArrayList<Book>();

		if (json == null) {
			return list;
		}

		JSONArray array = null;
		try {
			json = json.substring(json.indexOf("{"));
			JSONObject object = new JSONObject(json);
			array = object.getJSONArray(BOOKS);
		} catch (JSONException e) {
			System.out.println(e);
			return list;
		} catch (IndexOutOfBoundsException e) {
			System.out.println(e);
			return list;
		}

		for (int i = 0; i < array.length(); i++) {
			try {
				JSONObject item = (JSONObject) array.get(i);
				list.add(convertJsonObjectToBook(item));
			} catch (JSONException e) {
				System.out.println(e);
			} catch (IndexOutOfBoundsException e) {
				System.out.println(e);
			}
		}

		return list;
	}

	private static Book convertJsonObjectToBook(JSONObject item) throws JSONException {

		Book book = new Book();

		if (item.has(ID)) {
			book.id = item.getString(ID);
		}
		if (item.has(NAME)) {
			book.name = item.getString(NAME);
		}
		if (item.has(PRICE)) {
			book.price = item.getString(PRICE);
		}
		if (item.has(DESCRIPTION)) {
			book.description = item.getString(DESCRIPTION);
		}
		if (item.has(URL)) {
			book.url = item.getString(URL);
		}

		return book;
	}

	public static String convertBooksListToJson(ArrayList<Book> books) {
		JSONObject object = new JSONObject();
		JSONArray array = new JSONArray();

		if (books != null) {
			for (Book book : books) {
				try {
					array.put(convertBookToJson(book));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}

		try {
			object.put(BOOKS, array);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return object.toString();
	}

	private static JSONObject convertBookToJson(Book book) throws JSONException {
		JSONObject item = new JSONObject();

		if (book.id != null) {
			item.put(ID, book.id);
		}
		if (book.name != null) {
			item.put(NAME, book.name);
		}
		if (book.price != null) {
			item.put(PRICE, book.price);
		}
		if (book.description != null) {
			item.put(DESCRIPTION, book.description);
		}
		if (book.url != null) {
			item.put(URL, book.url);
		}

		return item;
	}

}
